{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2b24816a",
   "metadata": {},
   "source": [
    "## 1. API 币本位合约行情接口总览"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93d6b974",
   "metadata": {},
   "source": [
    "|方法|解释|Path|\n",
    "|:---|:---|:---|\n",
    "|get_ping|测试服务器连通性 PING|/dapi/v1/ping|\n",
    "|get_time|获取服务器时间|/dapi/v1/time|\n",
    "|get_exchangeInfo|获取交易规则和交易对|/dapi/v1/exchangeInfo|\n",
    "|get_depth|深度信息|/dapi/v1/depth|\n",
    "|get_trades|近期成交|/dapi/v1/trades|\n",
    "|get_historicalTrades|查询历史成交 (MARKET_DATA)|/dapi/v1/historicalTrades|\n",
    "|get_aggTrades|近期成交(归集)|/dapi/v1/aggTrades|\n",
    "|get_premiumIndex|最新现货指数价格和Mark Price|/dapi/v1/premiumIndex|\n",
    "|get_fundingRate|查询永续合约资金费率历史|/dapi/v1/fundingRate|\n",
    "|get_fundingInfo|查询资金费率信息|/dapi/v1/fundingInfo|\n",
    "|get_klines|K线数据|/dapi/v1/klines|\n",
    "|get_continuousKlines|连续合约K线数据|/dapi/v1/continuousKlines|\n",
    "|get_indexPriceKlines|价格指数K线数据|/dapi/v1/indexPriceKlines|\n",
    "|get_markPriceKlines|标记价格K线数据|/dapi/v1/markPriceKlines|\n",
    "|get_premiumIndexKlines|溢价指数K线数据|/dapi/v1/premiumIndexKlines|\n",
    "|get_ticker_24hr|24hr价格变动情况|/dapi/v1/ticker/24hr|\n",
    "|get_ticker_price|最新价格|/dapi/v1/ticker/price|\n",
    "|get_ticker_bookTicker|当前最优挂单|/dapi/v1/ticker/bookTicker|\n",
    "|get_constituents|查询指数价格成分|/dapi/v1/constituents|\n",
    "|get_openInterest|获取未平仓合约数|/dapi/v1/openInterest|\n",
    "|get_delivery_price|季度合约历史结算价|/futures/data/delivery-price|\n",
    "|get_openInterestHist|合约持仓量|/futures/data/openInterestHist|\n",
    "|get_topLongShortAccountRatio|大户账户数多空比|/futures/data/topLongShortAccountRatio|\n",
    "|get_topLongShortPositionRatio|大户持仓量多空比|/futures/data/topLongShortPositionRatio|\n",
    "|get_globalLongShortAccountRatio|多空持仓人数比|/futures/data/globalLongShortAccountRatio|\n",
    "|get_takerBuySellVol|合约主动买卖量|/futures/data/takerBuySellVol|\n",
    "|get_basis|基差|/futures/data/basis|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b552272",
   "metadata": {},
   "source": [
    "## 2. 模型实例化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "65d697f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "from binance_interface.api import CM\n",
    "from binance_interface.app.utils import eprint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b1eb7cf6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 转发：需搭建转发服务器，可参考：https://github.com/pyted/binance_resender\n",
    "proxy_host = None\n",
    "cm = CM(\n",
    "    proxy_host=proxy_host\n",
    ")\n",
    "market = cm.market"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f1eece3",
   "metadata": {},
   "source": [
    "## 3. U本位合约实时行情"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6694f518",
   "metadata": {},
   "source": [
    "### 3.1 当前最优挂单 get_ticker_bookTicker"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6201ba3d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'symbol': 'BTCUSD_PERP',\n",
      "           'pair': 'BTCUSD',\n",
      "           'bidPrice': '40148.0',\n",
      "           'bidQty': '620',\n",
      "           'askPrice': '40148.1',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'ETHUSD_PERP',\n",
      "           'pair': 'ETHUSD',\n",
      "           'bidPrice': '2221.81',\n",
      "           'bidQty': '21727',\n",
      "           'askPrice': '2221.82',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'LINKUSD_PERP',\n",
      "           'pair': 'LINKUSD',\n",
      "           'bidPrice': '13.817',\n",
      "           'bidQty': '35',\n",
      "           'askPrice': '13.819',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'BNBUSD_PERP',\n",
      "           'pair': 'BNBUSD',\n",
      "           'bidPrice': '293.900',\n",
      "           'bidQty': '18',\n",
      "           'askPrice': '293.910',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'TRXUSD_PERP',\n",
      "           'pair': 'TRXUSD',\n",
      "           'bidPrice': '0.11355',\n",
      "           'bidQty': '773',\n",
      "           'askPrice': '0.11356',\n",
      "           '...': '......'},\n",
      "          '......'],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 现货全部产品\n",
    "bookTicker_result = market.get_ticker_bookTicker()\n",
    "eprint(bookTicker_result, data_length=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8da3dc91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'symbol': 'BTCUSD_PERP',\n",
      "           'pair': 'BTCUSD',\n",
      "           'bidPrice': '40148.0',\n",
      "           'bidQty': '624',\n",
      "           'askPrice': '40148.1',\n",
      "           '...': '......'}],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 现货单个交易对\n",
    "bookTicker_result = market.get_ticker_bookTicker(symbol='BTCUSD_PERP')\n",
    "eprint(bookTicker_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bda1004",
   "metadata": {},
   "source": [
    "### 3.2 最新价格 get_ticker_price"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "40799e86",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'symbol': 'ETHUSD_240329', 'ps': 'ETHUSD', 'price': '2258.71', 'time': 1706245526966},\n",
      "          {'symbol': 'BCHUSD_PERP', 'ps': 'BCHUSD', 'price': '235.76', 'time': 1706245508581},\n",
      "          {'symbol': 'GMTUSD_PERP', 'ps': 'GMTUSD', 'price': '0.25760', 'time': 1706245403885},\n",
      "          {'symbol': 'LTCUSD_240329', 'ps': 'LTCUSD', 'price': '67.13', 'time': 1706244859254},\n",
      "          {'symbol': 'RUNEUSD_PERP', 'ps': 'RUNEUSD', 'price': '4.1050', 'time': 1706245387936},\n",
      "          '......'],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 现货全部产品\n",
    "price_result = market.get_ticker_price()\n",
    "eprint(price_result, data_length=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "368ff57d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200, 'data': [{'symbol': 'BTCUSD_PERP', 'ps': 'BTCUSD', 'price': '40148.1', 'time': 1706245538962}], 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 现货单个产品\n",
    "price_result = market.get_ticker_price(symbol='BTCUSD_PERP')\n",
    "eprint(price_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7f128ce",
   "metadata": {},
   "source": [
    "### 3.3 24hr价格变动情况 get_ticker_24hr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ac315ca0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'symbol': 'UNIUSD_PERP',\n",
      "           'pair': 'UNIUSD',\n",
      "           'priceChange': '-0.002',\n",
      "           'priceChangePercent': '-0.035',\n",
      "           'weightedAvgPrice': '5.75000879',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'THETAUSD_PERP',\n",
      "           'pair': 'THETAUSD',\n",
      "           'priceChange': '-0.009',\n",
      "           'priceChangePercent': '-0.939',\n",
      "           'weightedAvgPrice': '0.94889503',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'SOLUSD_PERP',\n",
      "           'pair': 'SOLUSD',\n",
      "           'priceChange': '0.582',\n",
      "           'priceChangePercent': '0.668',\n",
      "           'weightedAvgPrice': '87.18539016',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'AAVEUSD_PERP',\n",
      "           'pair': 'AAVEUSD',\n",
      "           'priceChange': '0.470',\n",
      "           'priceChangePercent': '0.533',\n",
      "           'weightedAvgPrice': '88.24177045',\n",
      "           '...': '......'},\n",
      "          {'symbol': 'GMTUSD_PERP',\n",
      "           'pair': 'GMTUSD',\n",
      "           'priceChange': '0.00240',\n",
      "           'priceChangePercent': '0.940',\n",
      "           'weightedAvgPrice': '0.25543639',\n",
      "           '...': '......'},\n",
      "          '......'],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 现货全部产品\n",
    "hr24_result = market.get_ticker_24hr()\n",
    "eprint(hr24_result, data_length=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7feddc18",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'symbol': 'BTCUSD_PERP',\n",
      "           'pair': 'BTCUSD',\n",
      "           'priceChange': '279.5',\n",
      "           'priceChangePercent': '0.701',\n",
      "           'weightedAvgPrice': '39927.54529431',\n",
      "           '...': '......'}],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 现货单个产品\n",
    "hr24_result = market.get_ticker_24hr(symbol='BTCUSD_PERP')\n",
    "eprint(hr24_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f0b7086",
   "metadata": {},
   "source": [
    "## 4. 历史K线 get_klines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "30fd742b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2023-01-01 00:00:00 1672502400000\n",
      "2023-01-01 00:05:00 1672502700000\n"
     ]
    }
   ],
   "source": [
    "# 测试时间\n",
    "startDatetime = '2023-01-01 00:00:00'\n",
    "endDatetime = '2023-01-01 00:05:00'\n",
    "startTime = int(datetime.datetime.strptime(startDatetime, '%Y-%m-%d %H:%M:%S').timestamp() * 1000)\n",
    "endTime = int(datetime.datetime.strptime(endDatetime, '%Y-%m-%d %H:%M:%S').timestamp() * 1000)\n",
    "\n",
    "print(startDatetime, startTime)\n",
    "print(endDatetime, endTime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0fda057a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [[1672502640000, '16580.3', '16580.3', '16580.3', '16580.3', '......'],\n",
      "          [1672502700000, '16580.3', '16580.3', '16580.3', '16580.3', '......']],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 仅给定终止时间\n",
    "kline_result = market.get_klines(symbol='BTCUSD_PERP', interval='1m', endTime=endTime, limit=2)\n",
    "eprint(kline_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "923164c4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [[1672502400000, '16578.1', '16580.3', '16578.0', '16580.3', '......'],\n",
      "          [1672502460000, '16580.3', '16580.3', '16580.3', '16580.3', '......'],\n",
      "          [1672502520000, '16580.4', '16580.4', '16580.4', '16580.4', '......'],\n",
      "          [1672502580000, '16580.3', '16580.3', '16580.3', '16580.3', '......'],\n",
      "          [1672502640000, '16580.3', '16580.3', '16580.3', '16580.3', '......'],\n",
      "          [1672502700000, '16580.3', '16580.3', '16580.3', '16580.3', '......']],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "# 仅给定起始和终止时间\n",
    "kline_result = market.get_klines(\n",
    "    symbol='BTCUSD_PERP',\n",
    "    interval='1m',\n",
    "    startTime=startTime,  # 包括startTime\n",
    "    endTime=endTime,  # 包括endTime\n",
    ")\n",
    "eprint(kline_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "224d87fe",
   "metadata": {},
   "source": [
    "## 5. 深度信息 get_depth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "eca40e38",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': {'lastUpdateId': 844374293002,\n",
      "          'E': 1706245546602,\n",
      "          'T': 1706245546590,\n",
      "          'symbol': 'BTCUSD_PERP',\n",
      "          'pair': 'BTCUSD',\n",
      "          'bids': [['40148.0', '655'], ['40147.9', '1'], ['40147.8', '228'], ['40146.8', '1'], ['40146.7', '1']],\n",
      "          'asks': [['40148.1', '14131'], ['40148.2', '17'], ['40148.3', '4'], ['40148.5', '234'], ['40148.6', '54']]},\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "depth_result = market.get_depth(symbol='BTCUSD_PERP', limit=5)\n",
    "eprint(depth_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f11bf70e",
   "metadata": {},
   "source": [
    "## 6. 成交查询"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbcf295d",
   "metadata": {},
   "source": [
    "### 6.1 近期成交列表 get_trades"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a80e6d14",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'id': 720241178,\n",
      "           'price': '40148.0',\n",
      "           'qty': '26',\n",
      "           'baseQty': '0.06476039',\n",
      "           'time': 1706245546325,\n",
      "           '...': '......'},\n",
      "          {'id': 720241179,\n",
      "           'price': '40148.0',\n",
      "           'qty': '116',\n",
      "           'baseQty': '0.28893096',\n",
      "           'time': 1706245546763,\n",
      "           '...': '......'},\n",
      "          {'id': 720241180,\n",
      "           'price': '40148.0',\n",
      "           'qty': '5',\n",
      "           'baseQty': '0.01245392',\n",
      "           'time': 1706245546763,\n",
      "           '...': '......'},\n",
      "          {'id': 720241181,\n",
      "           'price': '40148.1',\n",
      "           'qty': '1',\n",
      "           'baseQty': '0.00249078',\n",
      "           'time': 1706245546963,\n",
      "           '...': '......'},\n",
      "          {'id': 720241182,\n",
      "           'price': '40148.1',\n",
      "           'qty': '11',\n",
      "           'baseQty': '0.02739856',\n",
      "           'time': 1706245546964,\n",
      "           '...': '......'}],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "trades_result = market.get_trades(symbol='BTCUSD_PERP', limit=5)\n",
    "eprint(trades_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cef1f67d",
   "metadata": {},
   "source": [
    "### 6.2  查询历史成交 get_historicalTrades"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "6f39992c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'id': 720241182,\n",
      "           'price': '40148.1',\n",
      "           'qty': '11',\n",
      "           'baseQty': '0.02739856',\n",
      "           'time': 1706245546964,\n",
      "           '...': '......'},\n",
      "          {'id': 720241183,\n",
      "           'price': '40148.0',\n",
      "           'qty': '1',\n",
      "           'baseQty': '0.00249078',\n",
      "           'time': 1706245548286,\n",
      "           '...': '......'},\n",
      "          {'id': 720241184,\n",
      "           'price': '40148.0',\n",
      "           'qty': '1',\n",
      "           'baseQty': '0.00249078',\n",
      "           'time': 1706245548286,\n",
      "           '...': '......'},\n",
      "          {'id': 720241185,\n",
      "           'price': '40148.1',\n",
      "           'qty': '1',\n",
      "           'baseQty': '0.00249078',\n",
      "           'time': 1706245548962,\n",
      "           '...': '......'},\n",
      "          {'id': 720241186,\n",
      "           'price': '40148.1',\n",
      "           'qty': '11',\n",
      "           'baseQty': '0.02739856',\n",
      "           'time': 1706245548962,\n",
      "           '...': '......'}],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "historicalTrades_result = market.get_historicalTrades(symbol='BTCUSD_PERP', limit=5)  # 这个接口需要key\n",
    "eprint(historicalTrades_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce4fddac",
   "metadata": {},
   "source": [
    "### 6.3  近期成交(归集) get_aggTrades "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "b6888c52",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': [{'a': 293255475, 'p': '40148.0', 'q': '44', 'f': 720241176, 'l': 720241178, '...': '......'},\n",
      "          {'a': 293255476, 'p': '40148.0', 'q': '121', 'f': 720241179, 'l': 720241180, '...': '......'},\n",
      "          {'a': 293255477, 'p': '40148.1', 'q': '12', 'f': 720241181, 'l': 720241182, '...': '......'},\n",
      "          {'a': 293255478, 'p': '40148.0', 'q': '2', 'f': 720241183, 'l': 720241184, '...': '......'},\n",
      "          {'a': 293255479, 'p': '40148.1', 'q': '12', 'f': 720241185, 'l': 720241186, '...': '......'}],\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "aggTrades_result = market.get_aggTrades(symbol='BTCUSD_PERP', limit=5)\n",
    "eprint(aggTrades_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9753923",
   "metadata": {},
   "source": [
    "## 7. 交易规范信息 get_exchangeInfo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "be530d44",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'code': 200,\n",
      " 'data': {'timezone': 'UTC',\n",
      "          'serverTime': 1706241611122,\n",
      "          'rateLimits': [{'rateLimitType': 'REQUEST_WEIGHT', 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 2400},\n",
      "                         {'rateLimitType': 'ORDERS', 'interval': 'MINUTE', 'intervalNum': 1, 'limit': 1200}],\n",
      "          'exchangeFilters': [],\n",
      "          'symbols': [{'symbol': 'BTCUSD_PERP',\n",
      "                       'pair': 'BTCUSD',\n",
      "                       'contractType': 'PERPETUAL',\n",
      "                       'deliveryDate': 4133404800000,\n",
      "                       'onboardDate': 1597042800000,\n",
      "                       '...': '......'},\n",
      "                      {'symbol': 'BTCUSD_240329',\n",
      "                       'pair': 'BTCUSD',\n",
      "                       'contractType': 'CURRENT_QUARTER',\n",
      "                       'deliveryDate': 1711699200000,\n",
      "                       'onboardDate': 1695974400000,\n",
      "                       '...': '......'},\n",
      "                      {'symbol': 'BTCUSD_240628',\n",
      "                       'pair': 'BTCUSD',\n",
      "                       'contractType': 'NEXT_QUARTER',\n",
      "                       'deliveryDate': 1719561600000,\n",
      "                       'onboardDate': 1703836800000,\n",
      "                       '...': '......'},\n",
      "                      {'symbol': 'ETHUSD_PERP',\n",
      "                       'pair': 'ETHUSD',\n",
      "                       'contractType': 'PERPETUAL',\n",
      "                       'deliveryDate': 4133404800000,\n",
      "                       'onboardDate': 1597734000000,\n",
      "                       '...': '......'},\n",
      "                      {'symbol': 'ETHUSD_240329',\n",
      "                       'pair': 'ETHUSD',\n",
      "                       'contractType': 'CURRENT_QUARTER',\n",
      "                       'deliveryDate': 1711699200000,\n",
      "                       'onboardDate': 1695974400000,\n",
      "                       '...': '......'},\n",
      "                      '......']},\n",
      " 'msg': ''}\n"
     ]
    }
   ],
   "source": [
    "exchangeInfo_result = market.get_exchangeInfo()\n",
    "eprint(exchangeInfo_result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
